<template>
	<div>
  <el-form class="login-form"
           status-icon
           :rules="loginRules"
           ref="loginForm"
           :model="loginForm"
           label-width="0">
    <!--<el-form-item prop="tenantId">
    	<el-select class="cellbac"
		    v-model="loginForm.tenantId"
        autocomplete="off"
        :popper-append-to-body="false"
		    filterable
		    remote
		    reserve-keyword
		    placeholder="请输入关键词"
		    :remote-method="remoteMethod"
		    @change="remoteChange"
		    :loading="loading">
		    <el-option
		      v-for="item in options"
		      :key="item.tenantId"
		      :label="item.tenantName"
		      :value="item.tenantId">
		    </el-option>
		    <i slot="prefix"
           class="icon-quanxian"></i>
		  </el-select>
    </el-form-item>-->
    <el-form-item prop="phone">
      <el-input size="small" class="cellbac"
                @keyup.enter.native="handleLogin"
                v-model="loginForm.phone"
                auto-complete="off"
                :placeholder="$t('login.phone')">
        <i slot="prefix"
           class="icon-shouji"></i>
      </el-input>
    </el-form-item>
    <el-form-item prop="code">
      <el-row :span="24" >
        <el-col :span="16" class="cellbac">
          <el-input size="small"
                    @keyup.enter.native="handleLogin"
                    v-model="loginForm.code"
                    auto-complete="off"
                    :placeholder="$t('login.code')">
            <i slot="prefix" class="icon-yanzhengma"/>
          </el-input>
        </el-col>
        <el-col :span="8" class="cellbac">
          <div class="el-input-group__append" style="padding: 0 25px;">
          	<span class="msg-text" @click="handleSend" :class="[{display:msgKey}]">{{msgText}}</span>
          </div>
        </el-col>
      </el-row>
    </el-form-item>
    <!--<el-form-item prop="code">
      <el-input size="small" class="cellbac"
                @keyup.enter.native="handleLogin"
                v-model="loginForm.code"
                auto-complete="off"
                :placeholder="$t('login.code')">
        <i slot="prefix"
           class="icon-yanzhengma"
           style="margin-top:6px;"></i>
        <template slot="append">
          <span @click="handleSend"
                class="msg-text"
                :class="[{display:msgKey}]">{{msgText}}</span>
        </template>
      </el-input>
    </el-form-item>-->
    <el-form-item>
      <el-button size="small"
                 type="primary"
                 @click.native.prevent="handleLogin"
                 class="login-submit">{{$t('login.submit')}}</el-button>
    </el-form-item>
  </el-form>
  <div tabindex="-1" class="el-message-box__wrapper" style="z-index: 2250;" v-show="showSelectTenant">
  	<div class="el-message-box">
  		<div class="el-message-box__header">
  			<div class="el-message-box__title">
  				<span>请选择学校或机构</span>
  			</div>
  		</div>
			<div class="el-message-box__content">
				<div class="el-message-box__container">
					<div class="el-message-box__message">
						<p>
							<el-card class="box-card" style="height: 320px;overflow-y: auto;">
							  <div v-for="o in userTenantList" :key="o.tenantId" class="text item ulist" @click="selectedTenent(o.tenantId)">
							    <el-link type="primary" :underline="false">{{o.tenantName}}</el-link>
							    <i class="el-icon-arrow-right ulist_right"></i>
							  </div>
							</el-card>
						</p>
					</div>
				</div>
			</div>
 		</div>
 	</div>
 	<div class="v-modal" tabindex="0" style="z-index: 2240;" v-show="showSelectTenant"></div>
 	</div>
</template>

<script>
import { isvalidatemobile } from "@/util/validate";
import { mapGetters } from "vuex";
import {getMsgCode, findTenList, getTenList, changeTenant } from '@/api/user'
import {Message} from 'element-ui'
export default {
  name: "codelogin",
  data() {
    const validatePhone = (rule, value, callback) => {
      if (isvalidatemobile(value)[0]) {
        callback(new Error(isvalidatemobile(value)[1]));
      } else {
        callback();
      }
    };
    const validateCode = (rule, value, callback) => {
      if (value.length != 6) {
        callback(new Error("请输入6位数的验证码"));
      } else {
        callback();
      }
    };
    return {
    	options: [],
      list: [],
      loading: false,
      msgText: "",
      msgTime: "",
      msgKey: false,
      loginForm: {
        tenantId: "",
        phone: "",
        code: ""
      },
      userTenantList: {},
      showSelectTenant: false,
      ctrUser: {},
      loginRules: {
        //tenantId: [{required: false, message: "请输入租户ID", trigger: "click"}],
        phone: [{ required: true, trigger: "blur", validator: validatePhone }],
        code: [{ required: true, trigger: "blur", validator: validateCode }]
      }
    };
  },
  created() {
    this.msgText = this.config.MSGINIT;
    this.msgTime = this.config.MSGTIME;
  },
  mounted() {},
  computed: {
    ...mapGetters(["tagWel"]),
    config() {
      return {
        MSGINIT: this.$t("login.msgText"),
        MSGSCUCCESS: this.$t("login.msgSuccess"),
        MSGTIME: 60
      };
    }
  },
  props: [],
  methods: {
  	remoteMethod(query) {
        if (query !== '') {
          this.loading = true;
          findTenList(query).then(res => {
	          this.loading = false;
	          this.options = res.data.data;
	        })
        } else {
          this.options = [];
        }
      },
      remoteChange(val) {
      	var option = this.options.filter(item => {
              return 	item.tenantId == val
        });
        this.tenantName = option[0].tenantName;
      },
    handleSend() {
      if (this.msgKey) return;
      this.msgText = this.msgTime + this.config.MSGSCUCCESS;
      this.msgKey = true;
      getMsgCode(this.loginForm.phone).then(res => {});
      const time = setInterval(() => {
        this.msgTime--;
        this.msgText = this.msgTime + this.config.MSGSCUCCESS;
        if (this.msgTime == 0) {
          this.msgTime = this.config.MSGTIME;
          this.msgText = this.config.MSGINIT;
          this.msgKey = false;
          clearInterval(time);
        }
      }, 1000);
    },
    selectedTenent(tenantId) {
      	const loginfo = this.ctrUser;
      	const param = {
			    "roles": loginfo.authority.split(","),
			    "oauthId": loginfo.oauthId,
			    "user": {
			        "id": loginfo.userId,
			        "tenantId": tenantId,
			        "name": loginfo.userName,
			        "realName":loginfo.userName,
			        "account": loginfo.account,
			        "gradeId": loginfo.gradeId,
			        "roleId": loginfo.roleId
			    }
				};
				const _this = this;
				changeTenant(param).then((res) => {
					const user = res.data.data;
					user.changeTenant = "changeTenant"
					_this.$store.dispatch("LoginByPhone", user);
					_this.$router.push({path: this.tagWel.value});
				});
      },
    handleLogin() {
    	/*if(!this.loginForm.tenantId) {
    		 Message({
		      message: "请选择所属学校或机构",
		      type: 'error'
		    })
    		 return;
    	}*/
      this.$refs.loginForm.validate(valid => {
        if (valid) {
        	const loading = this.$loading({
              lock: true,
              text: '登录中,请稍后。。。',
              spinner: "el-icon-loading"
            });
          this.$store.dispatch("LoginByPhone", this.loginForm).then((res) => {
	        	const {account} = res;
	        	this.ctrUser = res;
	        	const loginfo = res;
	          getTenList({account}).then((rep) => {debugger
		        		const tenList = rep.data.data;
		        		this.userTenantList = rep.data.data;
		        		if(tenList&&tenList.length>1) {
	          		loading.close();
	          		const _this = this;
	          		setTimeout(function(){
	          			loading.close();
							     _this.showSelectTenant = true;
				          },500)
		        		}else{
		        			const param = {
								    "roles": loginfo.authority.split(","),
								    "oauthId": loginfo.oauthId,
								    "user": {
								        "id": loginfo.userId,
								        "tenantId": tenList[0].tenantId,
								        "name": loginfo.userName,
								        "realName":loginfo.userName,
								        "account": loginfo.account,
								        "gradeId": loginfo.gradeId,
								        "roleId": loginfo.roleId
								    }
									};
									const _this = this;
									changeTenant(param).then((res) => {
										const user = res.data.data;
										user.changeTenant = "changeTenant"
										_this.$store.dispatch("LoginByPhone", user);
										loading.close();
										_this.$router.push({path: this.tagWel.value});
									});
		        		}
		        	})
          }).catch(() => {
            loading.close()
          });
        }
      });
    }
  }
};
</script>

<style>
.msg-text {
  display: block;
  width: 60px;
  font-size: 12px;
  text-align: center;
  cursor: pointer;
}
.msg-text.display {
  color: #ccc;
}
.cellbac .el-select-dropdown__item>span {
	display: inline-block;
	margin-bottom: 12px;
}
/deep/ .el-select-dropdown {
	.el-scrollbar{
		.el-scrollbar__view  {
			.el-select-dropdown__item{
				display: inline-block;
	margin-bottom: 12px;
			}
		}
	}
}
/deep/.el-select-dropdown__wrap.el-scrollbar__wrap {
    margin-bottom: 0 !important;
  }
  .ulist {
  	border-bottom: 1px solid #ccc;
    line-height: 40px;
    cursor: pointer;
  }
  .ulist_right{
  	display: inline-block;
    float: right;
    margin-top: 18px;
  }
</style>
